#!/bin/bash

# Report to Slack Webhook disk status if one of two thresholds are exceeded
# Please go to the following Slack link for details of setting up an Incoming Slack Webhook
# https://api.slack.com/incoming-webhooks

. "$HELLO_IT_SCRIPT_SH_LIBRARY/com.github.ygini.hello-it.scriptlib.sh"

function informIT {

	user_name=$(whoami)
	device_record=$(dscl . list Computers | grep -v localhost)

	if [ ! -z $device_record ]
	then
		# Computer name may be different to hostname.  Get the record name
		device_domain=$(dscl . read Computers/"$device_record" OriginalNodeName 2>/dev/null | awk '{print $NF}')
		# Returns empty if current user is not a directory user
		user_phone_number=$(dscl "$device_domain" read /Users/$user_name PhoneNumber  2>/dev/null | tail -1)
	else
		user_phone_number=""
	fi

	sw_version=$(sw_vers -productVersion)
	client_version=$(defaults read /usr/local/sbin/FileWave.app/Contents/Info.plist  CFBundleLongVersionString)

	# Slack Webhook
	slack_webhook=$(defaults read /usr/local/etc/com.filewave.slack slack_webhook)
	slack_channel=$(defaults read /usr/local/etc/com.filewave.slack slack_channel)

	# Current FileWave client name
	filewave_client_name=$(defaults read /usr/local/etc/fwcld.plist fwUser)

	# Get time to post into footer
	now=$(date +%s)

	# Request call back from IT
	function request_callback {

		json="{
			\"username\": \"Helpdesk\",
			\"icon_emoji\": \":computer:\",
			\"channel\": \"#${slack_channel}\",
			\"text\": \":warning: *Request Callback: ${filewave_client_name}*\",
			\"attachments\": [
						{
						\"color\": \"#ffe100\",
						\"pretext\": \"*Message from $user_name*\",
						\"text\": \"*Please call back:* $user_phone_number\",
						\"footer\": \"macOS: $sw_version, client: ${client_version}\",
						\"ts\": \"$now\"
					}
			]
		}"
	}

	request_callback

	# Post to slack
	curl -X POST --data-urlencode "payload=$json" "$slack_webhook"
}

function onClickAction {
    informIT $@
}

main $@

exit 0
